#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

# $Id$

import wx
import wx.aui
import wx.py as py

import os
#import os.path

import sys, time

import connDB
import SDTM_edit
import NewDataset
import SDTMVAR_edit

import re

import SASReport_generator

import pythoneditor
import saslog
import saseditor
import sasenhancededitor

import proj_config


import about

# the path for this file
# correct error __file__ raised for py2exe: http://www.py2exe.org/index.cgi/WhereAmI
#_thisProgramDir = os.path.dirname(__file__)
#_thisProgramDir = os.path.dirname(sys.executable)
_thisProgramDir = os.path.dirname(sys.argv[0])
#_thisDir = os.path.dirname(__file__)
#_script = os.path.basename(__file__)
#_thisdir, _script = os.path.split(__file__)

class createauiNoteBook(wx.aui.AuiNotebook):
    def __init__(self, parent, dbfilepath=""):

        wx.aui.AuiNotebook.__init__(self, parent)
        
    
        
        self.pageTitles = ['BestPharm Protocolxxx']
        
        self.splitter = wx.SplitterWindow(self, style=wx.SP_3D| wx.SP_LIVE_UPDATE)
        self.paneltop = wx.Panel(self.splitter)
        self.panelbottom = wx.Panel(self.splitter)
        self.panelbottom.SetBackgroundColour('light blue')

        
        self.lstCtrl = wx.ListCtrl(self.paneltop,style=wx.LC_REPORT | wx.EXPAND)
    
        
        self.connDB = connDB.connDB(dbfilepath)
        
        for i,header in enumerate(self.connDB.headers):
            self.lstCtrl.InsertColumn(i, header[0])
            self.lstCtrl.SetColumnWidth(i, header[1])
    
        for i,firstcolname in enumerate(self.connDB.firstcol):
            self.lstCtrl.InsertStringItem(i, firstcolname)
            
            for j,col in enumerate(self.connDB.rows[i]):
                if j > 0:
                    if col == None:
                        self.lstCtrl.SetStringItem(i, j, u" ")
                    else:
                        self.lstCtrl.SetStringItem(i, j, col)
                        
                
        self._SetItemBackgroundColor()
                
        self.lstCtrl.currentItem = 0
        
        # auto just the column width
        for i in range(self.lstCtrl.GetColumnCount()):
            self.lstCtrl.SetColumnWidth(i,wx.LIST_AUTOSIZE)
            
        self.sizertop = wx.BoxSizer(wx.VERTICAL)
        self.sizertop.Add(self.lstCtrl, 1, wx.EXPAND | wx.ALL, 3)
        self.paneltop.SetSizer(self.sizertop)
        
        #Bottom Panel
        self.SDTMEditor = SDTM_edit.CreateSDTMEditor(self.panelbottom, self.connDB.classlst)
        
        
        self.AddPage(self.splitter, self.pageTitles[0])
        
        self.splitter.SplitHorizontally(self.paneltop, self.panelbottom, sashPosition=0)
        
        # Set the default Sash Position
        self.splitter.SetSashPosition(350)
        self.splitter.SetMinimumPaneSize(50)
    
        
        #when selected, show items in panelbottom
        #import DatasetSelected
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.EvtOnItemSelected, self.lstCtrl)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.EvtOnItemDoubleClicked, self.lstCtrl)
        
        #self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.EvtOnAuiClose, self)
        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.EvtOnAuiClose, self)
        
        self.Bind(wx.EVT_BUTTON, self.EvtOnSave, self.SDTMEditor.save)
        self.Bind(wx.EVT_BUTTON, self.EvtOnDiscard, self.SDTMEditor.discard)
        self.Bind(wx.EVT_BUTTON, self.EvtOnNew, self.SDTMEditor.new)
        self.Bind(wx.EVT_BUTTON, self.EvtOnDelete, self.SDTMEditor.delete)
        self.Bind(wx.EVT_BUTTON, self.EvtOnClose, self.SDTMEditor.close)
        
        
        
        
    def _SetItemBackgroundColor(self):
        """
        Set the background color for item of the list ctrl
        """
        
        item_cnt = self.lstCtrl.GetItemCount()
        
        for i in range(item_cnt):
            if i % 2 == 0:
                self.lstCtrl.SetItemBackgroundColour(i, "light blue")
            else:
                self.lstCtrl.SetItemBackgroundColour(i, "white")
        
    def EvtOnSave(self, event):
        """
        Save record
        """
        
        idx = self.lstCtrl.GetFocusedItem()
        column_cnt = self.lstCtrl.GetColumnCount()
        
        #Save in database
        domain=self.lstCtrl.GetItemText(idx)
        
        #DESCRIPTION,CLASS,STRUCTURE,PURPOSE,KEYVAR,COMMENTS,VERSION
        _description = self.SDTMEditor.te2.GetValue()
        _class = self.SDTMEditor.te3.GetValue()
        _structure = self.SDTMEditor.te4.GetValue()
        _purpose = self.SDTMEditor.te5.GetValue()
        _keyvar = self.SDTMEditor.te6.GetValue()
        _comments = self.SDTMEditor.te7.GetValue()
        _version = self.SDTMEditor.te8.GetValue()
        
        rows = (domain, _description, _class, _structure, _purpose, _keyvar, _comments, _version)
        
        sql = "update SDTM_DATASETS \
                set DESCRIPTION = '%s',\
                    CLASS = '%s',\
                    STRUCTURE = '%s',\
                    PURPOSE = '%s',\
                    KEYVAR = '%s',\
                    COMMENTS = '%s',\
                    VERSION = '%s'\
                    where DATASET = '%s'" % \
                (_description, _class, _structure, _purpose, _keyvar, _comments, _version, domain)
        self.connDB.Execute(sql)
        self.connDB.Commit()
        
        #Update list ctrl
        for i in range(column_cnt):
            if i > 1:
                self.lstCtrl.SetStringItem(idx,i, rows[i])
        
        dlg = wx.MessageDialog(self, 'Dataset %s Saved!' % domain , 'Information', wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()



    def EvtOnDiscard(self, event):
        """
        Discard any changes made to current record
        """
        
        try:

            currentItem = self.lstCtrl.GetFocusedItem()
            
            self.SDTMEditor.te1.SetValue("%s" % self.lstCtrl.GetItemText(currentItem))
            self.SDTMEditor.te2.SetValue("%s" % self.getColumnText(currentItem, 1))
            self.SDTMEditor.te3.SetValue("%s" % self.getColumnText(currentItem, 2))
            self.SDTMEditor.te4.SetValue("%s" % self.getColumnText(currentItem, 3))
            self.SDTMEditor.te5.SetValue("%s" % self.getColumnText(currentItem, 4))
            self.SDTMEditor.te6.SetValue("%s" % self.getColumnText(currentItem, 5))
            self.SDTMEditor.te7.SetValue("%s" % self.getColumnText(currentItem, 6))
            self.SDTMEditor.te8.SetValue("%s" % self.getColumnText(currentItem, 7))

        except:
            pass

    def EvtOnNew(self, event):
        """
        Create a New Dataset
        """
        
        # list of Dataset Name in list control
        Item_Cnt = self.lstCtrl.GetItemCount()
        Dataset = [self.lstCtrl.GetItemText(i) for i in range(Item_Cnt)]
        #dlg = wx.MessageDialog(self, 'Dataset %s ' % Dataset , 'Information', wx.OK | wx.ICON_INFORMATION)
        #dlg.ShowModal()
        #dlg.Destroy()
        
        import re
        # other than character a-z A-Z
        pattern = "[^a-zA-Z]+"
        p = re.compile(pattern)
        
        #dlg = wx.TextEntryDialog(self, 'Please Note: Dataset Name Should Contain Only Two Characters!', \
                                 #'Please Enter Dataset Name:', 'XX')
        
        dlg = NewDataset.NewDataset(self, classlst=self.connDB.classlst)
        
        if dlg.ShowModal() == wx.ID_OK:
            #print dlg.GetValue()
            (domain, class1, purpose, version) = dlg.GetValue()
            domain = domain.upper()
            
            dlg.Destroy()
            
            try:
                if Dataset.index(domain) >= 0:
                    dlg = wx.MessageDialog(self, 'Dataset %s Already Exists! Please Choose Another Name' % domain , 'Information', wx.OK | wx.ICON_INFORMATION)
                    dlg.ShowModal()
                    dlg.Destroy()
            except ValueError:
                if p.search(domain) is None and len(domain) == 2:
                    #create domain
                    
                    #First insert into the list ctrl
                    self.lstCtrl.InsertStringItem(Item_Cnt + 1, domain)
                    self.lstCtrl.SetStringItem(Item_Cnt, 1, "New Domain")
                    self.lstCtrl.SetStringItem(Item_Cnt, 2, class1)
                    self.lstCtrl.SetStringItem(Item_Cnt, 3, "One record per visit per subject")
                    self.lstCtrl.SetStringItem(Item_Cnt, 4, purpose)
                    self.lstCtrl.SetStringItem(Item_Cnt, 5, "STUDYID, USUBJID, ")
                    self.lstCtrl.SetStringItem(Item_Cnt, 6, "Study Specific.")
                    self.lstCtrl.SetStringItem(Item_Cnt, 7, version)
                    
                    #Then insert into database
                    sql = "insert into SDTM_DATASETS (DATASET, DESCRIPTION, CLASS, STRUCTURE, PURPOSE, KEYVAR, COMMENTS, VERSION) \
                          values ('%s', 'New Domain', '%s', 'One record per visit per subject', '%s', 'STUDYID, USUBJID, ', 'Study Specific.', '%s') " % (domain, class1, purpose, version)
                    self.connDB.Execute(sql)
                    self.connDB.Commit()
                    #At last, select this new row in list ctrl
                    self._SetItemBackgroundColor()
                    self.lstCtrl.Select(Item_Cnt)
                    self.lstCtrl.Focus(Item_Cnt)
                    
                    dlg = wx.MessageDialog(self, 'Dataset Name %s created!' % domain , 'Information', wx.OK | wx.ICON_INFORMATION)
                    dlg.ShowModal()
                    dlg.Destroy()

                else:
                    dlg = wx.MessageDialog(self, 'Dataset Name %s should only Contain two characters!' % domain , 'Information', wx.OK | wx.ICON_INFORMATION)
                    dlg.ShowModal()
                    dlg.Destroy()
                    



    def EvtOnDelete(self, event):
        """
        Delete record
        """
        
        idx = self.lstCtrl.GetFocusedItem()
        item_cnt = self.lstCtrl.GetItemCount()
        
        #Delete in database
        domain=self.lstCtrl.GetItemText(idx)
        sql = "delete * from SDTM_DATASETS where DATASET = '%s'" % domain
        self.connDB.Execute(sql)
        self.connDB.Commit()
        
        self.lstCtrl.DeleteItem(idx)
        
        if idx < item_cnt:
            self.lstCtrl.Select(idx)
        else:
            self.lstCtrl.Select(idx - 1)
            
        # Set Background Color again
        self._SetItemBackgroundColor()
        
    def EvtOnClose(self, event):
        """
        Close client window
        """
        
        self.connDB.Close()
        
        self.GetParent().Close()
        
        
    def EvtOnAuiClose(self, event):
        """
        when close the auiNoteBook page, if the page name is study name, then close client window
        """
        
        idx = self.GetSelection()
        PageTxt = self.GetPageText(idx)
        
        if PageTxt == self.pageTitles[0]:
            dlg = wx.MessageDialog(self,  'Close this page %s, will also close this window!!' % PageTxt ,
                                       'Warning',
                                       wx.OK | wx.ICON_INFORMATION
                                       #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                                       )
            dlg.ShowModal()
            dlg.Destroy()
            
            # Close the parent window
            self.GetParent().Close()

    
    def getColumnText(self, index, col):
        item = self.lstCtrl.GetItem(index, col)
        return item.GetText()
    
    def EvtOnItemSelected(self, event):
        """
        when item in dataset listctrl is selected, show items in the SDTM_edit panel
        """
        currentItem = event.m_itemIndex
        
        self.SDTMEditor.te1.SetValue("%s" % self.lstCtrl.GetItemText(currentItem))
        self.SDTMEditor.te2.SetValue("%s" % self.getColumnText(currentItem, 1))
        self.SDTMEditor.te3.SetValue("%s" % self.getColumnText(currentItem, 2))
        self.SDTMEditor.te4.SetValue("%s" % self.getColumnText(currentItem, 3))
        self.SDTMEditor.te5.SetValue("%s" % self.getColumnText(currentItem, 4))
        self.SDTMEditor.te6.SetValue("%s" % self.getColumnText(currentItem, 5))
        self.SDTMEditor.te7.SetValue("%s" % self.getColumnText(currentItem, 6))
        self.SDTMEditor.te8.SetValue("%s" % self.getColumnText(currentItem, 7))
        
        
        self.SDTMEditor.save.Enable()
        self.SDTMEditor.discard.Enable()
        self.SDTMEditor.delete.Enable()
        
        
    def EvtOnItemDoubleClicked(self, event):
        """
        when item in dataset listctrl is double clicked, add new page to notebook
        """
        currentItem = event.m_itemIndex
        
        pageTitle = self.lstCtrl.GetItemText(currentItem)
          
        pageCount = self.GetPageCount()
        pageTexts = [self.GetPageText(index) for index in range(pageCount) ]
        
        #dlg = wx.MessageDialog(self,  'pageTitles: %s ' % self.pageTitles ,
        #                       'Information',
        #                       wx.OK | wx.ICON_INFORMATION
        #                       #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
        #                       )
        #dlg.ShowModal()
        #dlg.Destroy()
            
        # If already open, then switch to that page.
        if pageTitle in pageTexts:
                        
            try:
                pageIndex = pageTexts.index(pageTitle)

                #dlg = wx.MessageDialog(self,  '%s already opened!' % pageTitle ,
                #               'Warning',
                #               wx.OK | wx.ICON_INFORMATION
                #               #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                #               )
                #dlg.ShowModal()
                #dlg.Destroy()
            
                #self.GetPage(pageIndex).SetFocus()
                self.SetSelection(pageIndex)
                
                return None

            except ValueError:
                
                
                return None

        # Else, add new page for it.
        else:

            #parent.connDB.Execute("select * from SDTM_VARIABLES where [Domain] = '%s'" % pageTitle)
            sqlstr = "select * from SDTM_VARIABLES where [Domain] = '%s'" % pageTitle
            self.connDB.Execute(sqlstr)
            self.connDB.FetchOne()
            rows = self.connDB.GetRows()
            
            # If no observation, popup a messageDialog.
            if rows is None:
                dlg = wx.MessageDialog(self, \
                                'No observations in %s' % pageTitle , \
                                'Warning', \
                                wx.OK | wx.ICON_INFORMATION \
                                )
                dlg.ShowModal()
                dlg.Destroy()
                
                return None

            else:
                panelx = SDTMVAR_edit.CreateSDTMVarPage(self, pageTitle)
                
                self.AddPage(panelx, pageTitle, select=1)
                #index = self.GetPageCount()
                #self.SetSelection(0)
                #self.SetSelection(index - 1)



class MyFrame(wx.MDIParentFrame): 

    def __init__(self,parent=None,id=wx.ID_ANY): 
        #wx.Frame.__init__(self, parent, id, "GRS Metadata Management System", size=(1024, 768))
        wx.MDIParentFrame.__init__(self, parent, id, "SDS/ADaM Metadata Management System", size=(1024, 768))
        
        
        self.SetIcon(wx.Icon(_thisProgramDir+'\\pycon.ico', wx.BITMAP_TYPE_ICO))
        
        # time in the statusbar
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.timer.Start(1000)        
        
        toolbar = self.CreateToolBar()
        ##toolbar.AddSimpleTool(self.NewId(), images.getNewBitmap(),
        ##        "New", "Long help for 'New'") 
        #toolbar.Realize()
        #
        
        self.buildMenu()
        #self.createMenuBar()
        
        self.buildStatusBar()
        
        
    def OnTimer(self,event):
        t = time.localtime(time.time())
        st = time.strftime("%I:%M:%S", t)
        self.statusBar.SetStatusText("Time: %s" % st, 2)
        
    def buildStatusBar(self):
        self.statusBar = self.CreateStatusBar()
        self.statusBar.SetFieldsCount(3)
        self.statusBar.SetStatusWidths([-3,-2,-1])
        
    
    def buildMenu(self):
        
        [wxID_NEWPROJECT,
         wxID_OPENPROJECT,
         wxID_PROJCONFIG,
         wxID_OPENMETALIB, 
         wxID_BROWSEPRJECT,
         wxID_PREFERENCE,
         wxID_QUIT,
         
         
         wxID_TOC,
         wxID_COLUMN,
         wxID_SASReportor,
         
         wxID_PYCRUST,
         wxID_PYSHELL,
         wxID_PYTHONEDITOR,
         wxID_SASLOG,
         wxID_SASEEDIT,
         wxID_SASEDITOR,
         wxID_OPTIONS
         
        ] = [wx.NewId() for _init_ctrls in range(17)]
            
        #menuBar = wx.MenuBar(style=wx.MB_DOCKABLE)
        menuBar = wx.MenuBar(wx.MB_DOCKABLE)
        
        menu1 = wx.Menu()
        menu1.Append(wxID_NEWPROJECT, "&New Project...\tCtrl+N", "New Project...")
        menu1.Append(wxID_OPENPROJECT, "&Open Project...\tCtrl+O", "Open a Project")
        menu1.AppendSeparator()
        
        self.proj_conf = menu1.Append(wxID_PROJCONFIG, "Project Settings", "Setup Project Configaration")
        self.proj_conf.Enable(False)
        
        menu1.AppendSeparator()
        menu1.Append(wxID_OPENMETALIB, "&Open Meta_Lib Project", "Open the Meta_Lib Project")
        menu1.AppendSeparator()
        menu1.Append(wxID_BROWSEPRJECT, "&Browse All Projects...\tCtrl+B", "Browse Projects")
        menu1.AppendSeparator()
        menu1.Append(wxID_PREFERENCE, "&Preference...", "Setup System Preference")
        menu1.AppendSeparator() 
        menu1.Append(wxID_QUIT, "&Quit\tCtrl+Q", "Quit")
        menuBar.Append(menu1, "&Project")
        
        self.Bind(wx.EVT_MENU, self.OnNewWindow, id=wxID_NEWPROJECT)
        self.Bind(wx.EVT_MENU, self.OnOpenProject, id=wxID_OPENPROJECT)
        self.Bind(wx.EVT_MENU, self.OnProjConf, id=wxID_PROJCONFIG)
        
        self.Bind(wx.EVT_MENU, self.OnQuit, id=wxID_QUIT)
        
        #menubar = wx.MenuBar()  
        #file = wx.Menu()  
        #quit = wx.MenuItem(file, 1, '&Quit\tCtrl+q')  
        #quit.SetBitmap(wx.Bitmap('icons/bp_btn2.png'))         
        #file.AppendItem(quit)  
        #self.Bind(wx.EVT_MENU, self.onQuit, id=1)  
        #menubar.Append(file, '&File')  
        #self.SetMenuBar(menubar) 

        menu2 = wx.Menu()                                         
        menu2.Append(wx.NewId(), "&Copy", "Copy in status bar")  
        menu2.Append(wx.NewId(), "C&ut", "")   
        menu2.Append(wx.NewId(), "Paste", "")                     
        menu2.AppendSeparator()                              
        menu2.Append(wx.NewId(), "&Options...", "Display Options")
        menuBar.Append(menu2, "&Edit")
        
        datasetMenu = wx.Menu()                                         
        datasetMenu.Append(wx.NewId(), "&Copy", "Copy in status bar")  
        datasetMenu.Append(wx.NewId(), "C&ut", "")   
        datasetMenu.Append(wx.NewId(), "Paste", "")                     
        datasetMenu.AppendSeparator()                              
        datasetMenu.Append(wx.NewId(), "&Options...", "Display Options")
        menuBar.Append(datasetMenu, "&Dataset")
        
        variableMenu = wx.Menu()                                         
        variableMenu.Append(wx.NewId(), "&Copy", "Copy in status bar")  
        variableMenu.Append(wx.NewId(), "C&ut", "")   
        variableMenu.Append(wx.NewId(), "Paste", "")                     
        variableMenu.AppendSeparator()                              
        variableMenu.Append(wx.NewId(), "&Options...", "Display Options")
        menuBar.Append(variableMenu, "&Variable")        
        

        formatMenu = wx.Menu()                                         
        formatMenu.Append(wx.NewId(), "&Copy", "Copy in status bar")  
        formatMenu.Append(wx.NewId(), "C&ut", "")   
        formatMenu.Append(wx.NewId(), "Paste", "")                     
        formatMenu.AppendSeparator()                              
        formatMenu.Append(wx.NewId(), "&Options...", "Display Options")
        menuBar.Append(formatMenu, "&Format")
        
        datamappingMenu = wx.Menu()                                         
        datamappingMenu.Append(wx.NewId(), "&Copy", "Copy in status bar")  
        datamappingMenu.Append(wx.NewId(), "C&ut", "")   
        datamappingMenu.Append(wx.NewId(), "Paste", "")                     
        datamappingMenu.AppendSeparator()                              
        datamappingMenu.Append(wx.NewId(), "&Options...", "Display Options")
        menuBar.Append(datamappingMenu, "&Mapping")
        
        
        reportMenu = wx.Menu()                                         
        reportMenu.Append(wxID_TOC, "TOC - Table of Contents", "Titles and Footnotes")
        reportMenu.Append(wxID_COLUMN, "Column Definition", "Define Columns for TLs")
        reportMenu.AppendSeparator()
        reportMenu.Append(wxID_SASReportor, "SAS Report Generator", "Generate SAS Report from a Dataset")
        
        menuBar.Append(reportMenu, "&Report")
        
        self.Bind(wx.EVT_MENU, self.OnToc, id=wxID_TOC)
        self.Bind(wx.EVT_MENU, self.OnColumn, id=wxID_COLUMN)
        self.Bind(wx.EVT_MENU, self.OnSASReportor, id=wxID_SASReportor)
        
        
        toolMenu = wx.Menu()
        toolMenu.Append(wxID_PYCRUST, "PyCrust", "PyCrust, the Flakiest Python Shell")  
        toolMenu.Append(wxID_PYSHELL, "PyShell", "PyShell, the Flakiest Python Shell")
        toolMenu.Append(wxID_PYTHONEDITOR, "Python Editor", "A Python Editor using wx.stc.StyledTextCtrl")
        toolMenu.AppendSeparator()
        toolMenu.Append(wxID_SASEEDIT, "SAS Enhanced Editor", "SAS Enhanced Editor Window")
        toolMenu.Append(wxID_SASEDITOR, "SAS Editor", "SAS Editor Window")
        toolMenu.Append(wxID_SASLOG, "SAS Log", "SAS Log Window")
        toolMenu.AppendSeparator()
        toolMenu.Append(wxID_OPTIONS, "&Options...", "Set up options for system")
        
        menuBar.Append(toolMenu, "&Tools")
        
        self.Bind(wx.EVT_MENU, self.OnPyCrust, id=wxID_PYCRUST)
        self.Bind(wx.EVT_MENU, self.OnPyShell, id=wxID_PYSHELL)
        self.Bind(wx.EVT_MENU, self.OnPythonEditor, id=wxID_PYTHONEDITOR)
        
        self.Bind(wx.EVT_MENU, self.OnSASEEdit, id=wxID_SASEEDIT)
        self.Bind(wx.EVT_MENU, self.OnSasEditor, id=wxID_SASEDITOR)
        self.Bind(wx.EVT_MENU, self.OnSasLog, id=wxID_SASLOG)
        
        self.Bind(wx.EVT_MENU, self.OnOptions, id=wxID_OPTIONS)
        
        
        
        helpMenu = wx.Menu()
        helpMenu.Append(wx.ID_ABOUT,"&About","About this system...")
        menuBar.Append(helpMenu,"&Help")
        
        self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
        
        
        self.SetMenuBar(menuBar)
        
        
        
    #def menuData(self): 
    #    return [("&File", (
    #                ("&New", "New Sketch file", self.OnNew),
    #                ("&Open", "Open sketch file", self.OnOpen),
    #                ("&Save", "Save sketch file", self.OnSave),
    #                ("", "", ""),
    #                ("&Color", (
    #                    ("&Black", "", self.OnColor,
    #                       wx.ITEM_RADIO),
    #                    ("&Red", "", self.OnColor,
    #                       wx.ITEM_RADIO),
    #                    ("&Green", "", self.OnColor,
    #                       wx.ITEM_RADIO),
    #                    ("&Blue", "", self.OnColor,
    #                       wx.ITEM_RADIO))),
    #                ("", "", ""),
    #                ("&Quit", "Quit", self.OnCloseWindow)))]
    #
    #def createMenuBar(self):
    #    menuBar = wx.MenuBar()
    #    for eachMenuData in self.menuData():
    #        menuLabel = eachMenuData[0]
    #        menuItems = eachMenuData[1]
    #        menuBar.Append(self.createMenu(menuItems), menuLabel)
    #    self.SetMenuBar(menuBar)
    #
    #def createMenu(self, menuData):
    #    menu = wx.Menu()
    #
    #    for eachItem in menuData:
    #        if len(eachItem) == 2:
    #            label = eachItem[0]
    #            subMenu = self.createMenu(eachItem[1])
    #            menu.AppendMenu(wx.NewId(), label, subMenu)
    #
    #        else:
    #            self.createMenuItem(menu, *eachItem)
    #    return menu
    #
    #def createMenuItem(self, menu, label, status, handler,
    #                   kind=wx.ITEM_NORMAL):
    #    if not label:
    #        menu.AppendSeparator()
    #        return
    #    menuItem = menu.Append(-1, label, status, kind)
    #    self.Bind(wx.EVT_MENU, handler, menuItem)        

        
#        self.textbox = wx.StaticText(panel, wx.ID_ANY, "Pos:", pos=(10, 12)) 
#        self.posCtrl = wx.TextCtrl(panel, wx.ID_ANY, "", pos=(40, 10))
        
#        self.btn = wx.Button(panel,label="hello",pos=(125, 30), size=(150, 50))
#        self.btn2 = wx.Button(panel,label="hello2",pos=(125, 100), size=(150, 50)) 
        
#        self.Bind(wx.EVT_BUTTON, self.OnClickbtn, self.btn)
        
    #def OnInit(self):
    #    self.SetTopWindow(self.panel)
    #    return True
    #    
    #def OnMove(self, event): 
    #    pos = event.GetPosition() 
    #    self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y))
    #    
    #
    #def OnClickbtn(self,event):
    #    if self.btn.GetLabel() == "Close Me":
    #        self.btn.SetLabel("hello")
    #        self.btn2.Enable(True)
    #        
    #    else:
    #        self.btn.SetLabel("Close Me")
    #        self.btn2.Enable(False)
        
    def OnNewWindow(self, event):
        """
        New Window
        """
        self.win = wx.MDIChildFrame(self, -1, "Project xxx Window")
        self.win.Centre()
        self.win.Maximize(True)
        
        self.win.SetIcon(wx.Icon(_thisProgramDir+'\\pycon.ico', wx.BITMAP_TYPE_ICO))
        
        #self.panel0 = wx.Panel(self.win, wx.ID_ANY)
        #self.panel0.SetBackgroundColour('Grey')

        #self.myflatNoteBook = createauiNoteBook(self.panel0)
        self.myflatNoteBook = createauiNoteBook(self.win)
        
        self.win.Show(True)
        
        # Enable menu Project configuration
        self.proj_conf.Enable(True)
        
    def OnOpenProject(self, event):
        """
        Open a Project file, a mdb file
        """
        #wildcard = "Python source (*.py)|*.py|"     \
           #"Compiled Python (*.pyc)|*.pyc|" \
           #"SPAM files (*.spam)|*.spam|"    \
           #"Egg file (*.egg)|*.egg|"        \
           #"All files (*.*)|*.*"
        wildcard = "Microsoft Access File (*.mdb)|*.mdb"
        
        dlg = wx.FileDialog(
            self, message="Please Choose a Project File",
            defaultDir=_thisProgramDir, 
            defaultFile="",
            wildcard=wildcard,
            style=wx.FD_OPEN | wx.FD_CHANGE_DIR
            )

        # Show the dialog and retrieve the user response. If it is the OK response, 
        # process the data.
        if dlg.ShowModal() == wx.ID_OK:
            # This returns a Python list of files that were selected.
            filepath = dlg.GetPath()
            
            #msgdlg = wx.MessageDialog(self,  'File Name is %s!' % filepath ,
            #                           'Warning',
            #                           wx.OK | wx.ICON_INFORMATION
            #                           #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
            #                           )
            #msgdlg.ShowModal()
            #msgdlg.Destroy()
        #elif dlg.ShowModal() == wx.ID_CANCEL:
        #    return
        else:
            return False

        dlg.Destroy()
        
        
        # Connect to this access mdb file;
        
        self.win = wx.MDIChildFrame(self, -1, "Project xxx Window")
        self.win.Centre()
        self.win.Maximize(True)
        
        self.win.SetIcon(wx.Icon(_thisProgramDir+'\\pycon.ico', wx.BITMAP_TYPE_ICO))
        
        self.myflatNoteBook = createauiNoteBook(self.win, filepath)
        
        # Set window title;
        self.win.SetLabel(filepath)
        
        self.win.Show(True)
        
        # Enable menu Project configuration
        self.proj_conf.Enable(True)
        
        
    def OnProjConf(self, event):
        """
        Open a Project Configaration
        """
        
        proj_config.project_config(self)
        
        
    def OnQuit(self, event):
        """
        Quit the application.
        """
        self.Close()
        
        
    def OnToc(self, event):
        
        dlg = wx.MessageDialog(self, 'Edit TOC ...', 'Information', wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()
        
        
    def OnColumn(self, event):
        
        dlg = wx.MessageDialog(self, 'Edit Column for each TLs ...', 'Information', wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()
    
    
    def OnSASReportor(self, event):
        
        intro = 'SAS Report Generator Window'
        
        window = wx.FindWindowByName(intro, parent=self)
        
        if window is None:
            
            sasReportor = SASReport_generator.CreateSASReport(self, iconpath=_thisProgramDir)
        
        else:
            
            window.Activate()
            
            
    def OnPyCrust(self, event):
        
        intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % py.version.VERSION
        
        window = wx.FindWindowByName("PyCrust: %s" % intro, parent=self)
        
        if window is None:
            
            win = wx.MDIChildFrame(self, -1, "PyCrust: %s" % intro)
            win.Centre()
            win.Maximize(True)
            
            win.SetIcon(wx.Icon(_thisProgramDir+'\\pycon.ico', wx.BITMAP_TYPE_ICO))
            
            pycrust = py.crust.Crust(win, intro=intro)
            
            win.Show(True)
        
        else:
            
            window.Activate()
            
            
    def OnPyShell(self, event):
        
        
        intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % py.version.VERSION
        
        window = wx.FindWindowByName("PyShell: %s" % intro, parent=self)
        
        if window is None:
            
            win = wx.MDIChildFrame(self, -1, "PyShell: %s" % intro)
            win.Centre()
            win.Maximize(True)
            
            win.SetIcon(wx.Icon(_thisProgramDir+'\\pycon.ico', wx.BITMAP_TYPE_ICO))
            
            pyshell = py.shell.Shell(win, introText=intro)
            
            win.Show(True)
        
        else:
            
            window.Activate()
            
        
    def OnSASEEdit(self, event):
        
        window = wx.FindWindowByName("SAS Enhanced Editor Window", parent=self)
        
        if window is None:
            
            sas_enhanced_editor = sasenhancededitor.CreateSASEEdit(self, iconpath=_thisProgramDir)
        
        else:
            
            #msgdlg = wx.MessageDialog(self,  'Log window is open!',
            #                           'Warning',
            #                           wx.OK | wx.ICON_INFORMATION
            #                           #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
            #                           )
            #msgdlg.ShowModal()
            #msgdlg.Destroy()
            
            window.Activate()
            
            
    def OnPythonEditor(self, event):
        
        intro = 'Welcome To Python Editor'
        
        window = wx.FindWindowByName("Python Editor: %s" % intro, parent=self)
        
        if window is None:
            
            python_editor = pythoneditor.pythoneditor(self, iconpath=_thisProgramDir)
        
        else:
            
            #msgdlg = wx.MessageDialog(self,  'Log window is open!',
            #                           'Warning',
            #                           wx.OK | wx.ICON_INFORMATION
            #                           #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
            #                           )
            #msgdlg.ShowModal()
            #msgdlg.Destroy()
            
            window.Activate()
            
        
    def OnSasLog(self, event):
        
        window = wx.FindWindowByName("SAS Log Window", parent=self)
        
        if window is None:
            
            sas_log = saslog.CreateSASLog(self, iconpath=_thisProgramDir)
        
        else:
            
            #msgdlg = wx.MessageDialog(self,  'Log window is open!',
            #                           'Warning',
            #                           wx.OK | wx.ICON_INFORMATION
            #                           #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
            #                           )
            #msgdlg.ShowModal()
            #msgdlg.Destroy()
            
            window.Activate()
        
        
    def OnOptions(self, event):
        
        window = wx.FindWindowByName("System Options", parent=self)
        
        if window is None:
            
            sys_option = options.set_options(self, title="System Options")
        
        else:
            
            window.Activate()
            
            
        
    def OnSasEditor(self, event):
        
        window = wx.FindWindowByName("SAS Editor Window", parent=self)
        
        if window is None:
            
            sas_editor = saseditor.CreateSASEditor(self, iconpath=_thisProgramDir)
        
        else:
            
            #msgdlg = wx.MessageDialog(self,  'Log window is open!',
            #                           'Warning',
            #                           wx.OK | wx.ICON_INFORMATION
            #                           #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
            #                           )
            #msgdlg.ShowModal()
            #msgdlg.Destroy()
            
            window.Activate()
            
            
    def OnAbout(self, event):
        
        # Show about dialog
        self.about = about.AboutDlg(self, basepath=_thisProgramDir)
        

if __name__ == '__main__': 
    app = wx.PySimpleApp(redirect=False) 
    frame = MyFrame()
    frame.Centre()
    frame.Maximize(True)
    frame.Show(True) 
    app.MainLoop()
    
    
